package com.example.weather.control;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.weather.entity.Result;
import com.example.weather.model.Weather;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/weather")
public class WeatherController {

    @Value("${api.url}")
    private String url;

    @GetMapping("/city")
    @ResponseBody
    public Result<Weather> getWeather(@RequestParam("cityName") String cityName){
        Result<Weather> result = new Result<>();

        //传入的参数为空
        if (StrUtil.isEmpty(cityName)) {
            result.setMessage("传入的城市名为空");
            result.setCode(400);
            return result;
        }

        // 先访问api获得天气信息
        HttpResponse response = HttpRequest.get(url + cityName).execute();
        // 解析实体里面的信息
        String body = response.body();
        // 解析JSON响应
        JSON json = JSONUtil.parse(body);

        // 检查是否有错误信息
        if (json.getByPath("status") != null && "The location can not be found.".equals(json.getByPath("status").toString())) {
            result.setCode(400);
            result.setMessage("您输入的城市不存在");
            return result;
        }

        // 如果没有错误那么将传入进来的json字符串转换为对象
        Weather resultWeather = JSONUtil.toBean(body, Weather.class);

        result.setCode(200);
        result.setMessage("获取成功");
        result.setData(resultWeather);
        return result;
    }
}
